<template>
  <section v-loading="loading">
    <template v-if="!loading">
      <template v-if="tabList.length > 0">
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane v-for="item in tabList" :label="item.label" :key="item.value" :name="item.name" lazy></el-tab-pane>
        </el-tabs>
        <div class="content-box">
          <div class="title-top">
            <div>
              <ui-title :title="$t('common.pageTitle.pageSettingMessage')" />
              <p class="title-tip">{{$t('projectManage.setting.messageSetting.tip1')}}</p>
            </div>
            <div>
              <el-button class="create-btn" type="primary" @click="handleCreateRule()">{{ $t('message.setting.cusMes.t5') }}</el-button>
            </div>
          </div>
            <!-- 表格数据 -->
            <MessageTable 
              v-loading="contentLoading"
              style="margin:8px 0 36px;" 
              v-model="projectList"
              @getListByModule="fetchProjectMessList"
              :projectTypeId="currentTypeId"
              @handleEditColumn="handleEditColumn($event, 'base')"
              @handleDeleteColumn="handleDeleteColumn($event, 'base')"
              show-external-column
              show-operate-column
            />
        </div>
        <!-- 编辑规则弹窗 -->
        <project-message-rule ref="projectMessageRule" :projectTypeId="currentTypeId" @getListByModule="fetchProjectMessList"></project-message-rule>
      </template>
      <no-data-view-new v-else :notice-msg="$t('common.base.tip.noData')" />
    </template>
  </section>
</template>
<script>
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import MessageTable from '../table/MessageTable'
import ProjectMessageRule from '../dialog/ProjectMessageRule'
import { getProjectTypeField, projectTypeList, messageRuleList, deleteMessageRule } from '@src/api/ProjectManage.ts';
import { t } from '@src/locales'
import { projectSelectField } from '@src/modules/doMyself/setting/message/components/dialog/projectFixData.js'
import { isSubForm, canUseField } from '@src/util/function';

export default {
  data() {
    return {
      loading: false,
      contentLoading: false,
      tabList: [],
      module:'project', // 模块
      messageRruleCreatePedding: false,
      projectList: [],
      activeName: '', // 当前选中的tab
    }
  },
  provide(){
    return {
      module: this.module,
      projectData: {
        fields: [], // 项目类型的表单的field list
      }
    }
  },
  props: {
    projectTypeId:{
      type:String,
      default: '',
    }
  },
  components: {
    NoDataViewNew,
    MessageTable,
    ProjectMessageRule,
  },
  mounted(){
    // 获取tab数据
    this.getTabsList()

  },

  computed: {
    currentTypeId() {
      // if (this.projectTypeId) return this.projectTypeId
      // 获取当前被点击的项目类型id
      return this.tabList.filter((item) => item.name === this.activeName)[0]?.value
    },
  },
  methods: {
    // 获取项目类型列表
     async getTabsList() {
      try {
        let res = await projectTypeList();
        const { success, message, data } = res || {};
        if (!success) return this.$message.error(message)
        this.tabList = (data || []).map(item => {
          return {
            label: item.name,
            name: item.name,
            value: item.id + '',
          };
        });

        let tabItem = []
        // 当前选中的tab值
        if (this.projectTypeId) {
          tabItem = this.tabList.filter((item) => item.value === this.projectTypeId)?.[0]
        } else  {
          tabItem  = this.tabList[0]
        }
        this.activeName = tabItem.label

        await this.fetchFieldList(tabItem) // 获取对应表单的字段
        this.fetchProjectMessList()
      } catch (err) {
        console.log('error => fetchTemplateList', err);
      }
    },
    async handleTabClick(tab, event) {
      this.projectList = []
      const tabItem = this.tabList[tab.index]
      // this.activeTabItem = tabItem
      this._provided.activeForm = tabItem
      this.activeName = tab.name
      try {
        this.contentLoading = true
        await this.fetchFieldList(tabItem)
        await this.fetchProjectMessList()
      } catch {
         this.contentLoading = false
      }

    },

        /**
     * 描述 获取表单设计器的所有field
     * @date 2022-09-05
     * @returns {any}
     */
     async fetchFieldList(tabItem) {
      try {
        this.isLoadField = false

        let params = {
          tableName: 'project',
          templateId: tabItem.value
        }
        const res = await getProjectTypeField(params).finally(()=> this.isLoadField = true)
        if(res) {

          if (Array.isArray(res.data)) {
            // 过滤连接器字段
            res.data = res.data.filter(field => field.formType != 'connector')
          }
          
          this._provided.projectData.allfields = res.data
          this._provided.projectData.fields = [...projectSelectField, ...res.data].filter(field => canUseField(field) && !isSubForm(field) && !field?.isHidden).map(item=> {
            return {
              fieldValue: item.fieldName,
              fieldName: item.displayName,
              moduleId: item.fieldName,
              moduleName: 'project'
            }
          })
        }
      } catch(e) {
        this.$message.error(JSON.stringify(e))
      }
    },
    // 获取当前项目类型的消息设置列表
    fetchProjectMessList() {
      this.contentLoading = true
      messageRuleList({projectTypeId: this.currentTypeId}).then((res) => {
        this.contentLoading = false
        if (!res.success) return this.$message.error(res.message)
        this.projectList = res.data.map((item) => {
          return {
            ...item,
            title: item.ruleName
          }
        })
      })
    },

    //  删除规则
    handleDeleteColumn(row, type) { 
      this.$confirm(t('message.setting.cusMes.t7'), t('common.base.toast'), {
        confirmButtonText: t('common.base.makeSure'),
        cancelButtonText: t('common.base.cancel'),
        type: 'warning'
      }).then(async () => {
        try {
          let params = {
            id: row.id,
            projectTypeId: this.currentTypeId
          }
          deleteMessageRule(params).then((res)  =>  {
            if (!res.success) return this.$message.error(res.message)
            if (res.success) {
              // 重新获取列表
              this.fetchProjectMessList()
            }
          })
        } catch (e) {
          console.error('[fetch delete error]', e)
        }
      })


    },
    // 编辑规则
    handleEditColumn(row) {
      this.$refs.projectMessageRule.openDialog(row)
    },
    // 新建规则
    handleCreateRule() {
      this.$refs.projectMessageRule.openDialog()
    },

    // 编辑消息规则提交
    handeMessageSubmit()  {

    }
  }
}
</script>
<style lang="scss" scoped>
.create-btn{
    margin-top: 12px;
}
.content-box{
  height: calc(100% - 60px);
  .title-top {
    display: flex;
    justify-content:space-between;
    align-items: center;
    .title-tip {
      color: #7F7F7F;
      font-size: 13px;
      margin: 4px 0  0 6px;
    }
  }
}
.message-create-dialog ::v-deep .el-dialog{
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    margin:0 !important;
    .el-dialog__body {
      padding:16px 20px 12px;
      overflow-y: auto;
      max-height: calc(100vh - 100px);
    }

    overflow: visible;
    .el-dialog__header{
      border-radius: 8px 8px 0 0;
    }
    .el-dialog__headerbtn {
      top: 0;
    }
    .el-dialog__body {
      padding-bottom: 12px;
      .base-editor-container .ql-editor{
        height: 120px;
      }
    }
}
::v-deep .el-tabs {
  height: auto;
  .el-tabs__header{
      margin: 0 0 6px;
  }
}

</style>